package com.vickw.springcloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.concurrent.TimeUnit;

/**
 * @version 1.0
 * @Description：
 * @Author VickW
 * @Date 2022/3/18 23:45
 */
@Service
public class PaymentService {

    /*==============服务降级=============*/

    /**
     * @param id
     * @return
     * @methodName paymentInfo_OK
     * @Description: 正常访问肯定OK的方法
     **/
    public String paymentInfo_OK(Integer id) {
        return "线程池： " + Thread.currentThread().getName() + "  paymentInfo_OK,id:  " + id + "\t ♡♡♡♡♡♡♡ ";
    }


    @HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler",  // 超时或者异常的回调方法/兜底方法
            // 设置自身调用超时时间的峰值，峰值内可以正常运行，超过了需要兜底方法处理，做服务降级fallback
            commandProperties = {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")})
    public String paymentInfo_TimeOut(Integer id) {
        int timeNum = 3;
        // int a = 10 / 0;
        try {
            TimeUnit.SECONDS.sleep(timeNum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池： " + Thread.currentThread().getName() + "  paymentInfo_TimeOut,id:  " + id + "\t ♡♡♡♡♡♡♡ " + "耗时（秒）" + timeNum;
    }

    // paymentInfo_TimeOut方法超时或者出现异常的兜底方法
    public String paymentInfo_TimeOutHandler(Integer id) {
        return "线程池： " + Thread.currentThread().getName() + "  8001系统繁忙或者运行报错，请稍后再试,id: " + id;
    }


    /*==============服务熔断=============*/
    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",
            commandProperties = {
                    @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),// 是否开启断路器
                    @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),// 请求次数
                    @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"), // 时间窗口期 ms
                    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),// 失败率达到%多少后跳闸
            }) // 在10s内10次请求有60%失败 // 先看次数，再看百分比
    public String paymentCircuitBreaker(@PathVariable("id") Long id) {
        if (id < 0) {
            throw new RuntimeException("***********id,不能为负数***********");
        }
        // 等价于UUID.randomUUID().toString(); //pom中有hutool-all
        String serialNum = IdUtil.simpleUUID();
        return Thread.currentThread().getName() + "\t" + "调用成功，流水号 " + serialNum;
    }

    // 服务降级兜底方法
    public String paymentCircuitBreaker_fallback(@PathVariable("id") Long id){
        return "~~~~~~~~~~~~~~~id不能为负数，请稍后再试~~~~~~~~~~~~~~~~~~~";
    }


}
